var express = require('express');
var http = require("http");
var marked =require("marked");


var app = express();
//  主页输出 "Hello World"
app.get('/', function (req, res) {
    console.log("主页 GET 请求",req.query);
    if(req.query.md){
        rmd(req.query.md,function(resD){
            // res.writeHead(200, { 'Access-Control-Allow-Origin': '*', "Content-Type": resD.type });   //设置头，允许跨域
            // res.write(resD.html , "binary");
            // res.end();
            res.jsonp(resD.html);
        });
    }
})
var server = app.listen(8081, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("应用实例，访问地址为 http://%s:%s", host, port)

})

function rmd(getUrl,Fun){
    getUrl = getUrl.replace(/https/, "http");
    http.get(getUrl, function (response) {
        response.setEncoding('binary');  //二进制binary
        var type = response.headers["content-type"];
        var Data = '';
        response.on('data', function (data) {    //加载到内存
            Data += data;
        }).on('end', function () {          //加载完
            //console.log("加载完成",Data);
            Fun({
                html:marked(Data),
                type:type
            });
        })
    })
}